#include "server.h"

//Libraries
#include "config.h"
#include "logger.h"
#include "database.h"

//QT
#include <QCoreApplication>

//Run server
Server::Server() : output(stdout, QIODevice::WriteOnly)
{
    // Write info about start
    output << "Starting server  " << endl;
    output << "------------------" << endl;
    output.flush();

    // Load arguments
    argList << QCoreApplication::arguments();
    // delete first item (name of file)
    argList.removeFirst();

    // create config with given arguments
    Config *config = Config::instance();
    config->load(&argList);
    if (!config->loaded) {
        //QUIT APP
        QTimer::singleShot(0, qApp, SLOT(quit()));
    }

    // create logger
    Logger *logger = Logger::instance();
    // add listening ip and port to log
    QString logMsg;
    QTextStream(&logMsg) << "Listening IP: " << config->getValue("listening-ip");
    logger->log(logMsg,Logger::NOTICE);
    logMsg.clear();
    QTextStream(&logMsg) << "Listening PORT: " << config->getValue("listening-port");
    logger->log(logMsg,Logger::NOTICE);

    // create database
    Database db;
    if (!db.loaded) {
        //QUIT APP
        QTimer::singleShot(0, qApp, SLOT(quit()));
    }

    // create listener
    QHostAddress listenAddr(config->getValue("listening-ip"));
    if (!listener.listen(listenAddr,config->getValue("listening-port").toInt())) {
        logger->log("Cannot listen on selected address and port.",Logger::ERROR);
        //QUIT APP
        QTimer::singleShot(0, qApp, SLOT(quit()));
    }
    // set max connections
    listener.setMaxPendingConnections(config->getValue("max-connected-clients").toInt());

    // Write info about run
    output << "Server started" << endl;
    output.flush();
}



